<?php

/**
 * ECSHOP 支付宝插件
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: douqinghua $
 * $Id: allinpay.php 17217 2011-01-19 06:29:08Z douqinghua $
 */

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/allinpay.php';

if (file_exists($payment_lang))
{
    global $_LANG;

    include_once($payment_lang);
}

/* 模块的基本信息 */
if (isset($set_modules) && $set_modules == TRUE)
{
    $i = isset($modules) ? count($modules) : 0;

    /* 代码 */
    $modules[$i]['code']    = basename(__FILE__, '.php');

    /* 描述对应的语言项 */
    $modules[$i]['desc']    = 'allinpay_desc';

    /* 是否支持货到付款 */
    $modules[$i]['is_cod']  = '0';

    /* 是否支持在线支付 */
    $modules[$i]['is_online']  = '1';

    /* 作者 */
    $modules[$i]['author']  = 'ECSHOP TEAM';

    /* 网址 */
    $modules[$i]['website'] = 'http://www.allinpay.com';

    /* 版本号 */
    $modules[$i]['version'] = '1.0.2';

    /* 配置信息 */
    $modules[$i]['config']  = array(
        array('name' => 'allinpay_pc',           'type' => 'text',   'value' => ''),
        array('name' => 'allinpay_m',           'type' => 'text',   'value' => ''),
        array('name' => 'allinpay_key',               'type' => 'text',   'value' => ''),
        array('name' => 'allinpay_pay_method',        'type' => 'select', 'value' => '')
    );

    return;
}

/**
 * 类
 */
class allinpay
{

    /**
     * 构造函数
     *
     * @access  public
     * @param
     *
     * @return void
     */

	/* 代码修改_start  By  www.68ecshop.com */
    function __construct()
    {
        $this->allinpay();
    }

	 function allinpay()
    {
    }
	/* 代码修改_end  By  www.68ecshop.com */

    /**
     * 生成支付代码
     * @param   array   $order      订单信息
     * @param   array   $payment    支付方式信息
     */
    function get_code($order, $payment)
    {
        //获取用户通联userid
        $tl_user_id = $this->get_tl_user_id($_SESSION[user_id],$payment);
        $serverUrl = "";
        $inputCharset = 1;
        $pickupUrl = return_url(basename(__FILE__, '.php'));
        $receiveUrl = return_url(basename(__FILE__, '.php'));
        $version = "v1.0";
        $language = 1;
        $signType = 1;
        $merchantId = $payment[allinpay_m];
        $payerName = "";
        $payerEmail = '';
        $payerTelephone = "";
        $payerIDCard = "";
        $pid = "";
        $orderNo = $order['log_id'];
        $howmoney = $order['order_amount'];
        $orderAmount = $howmoney * 100;
        $orderDatetime = date('Ymdhis');
        $orderCurrency = "0";
        $orderExpireDatetime = "";
        $productName = "现金充值";
        $productId = $order['order_sn'];
        $productPrice = "";
        $productNum = "1";
        $productDescription = "";
        $ext1 = "<USER>".$tl_user_id."</USER>";
        $ext2 = "";
        $extTL=$_POST["extTL"];
        $payType = "0"; //payType   不能为空，必须放在表单中提交。
        $issuerId = ""; //issueId 直联时不为空，必须放在表单中提交。
        $pan = "";
        $tradeNature=$_POST["tradeNature"];
        $customsExt=$_POST["customsExt"];
        $key = $payment[allinpay_key];

        $bufSignSrc = "";
        if ($inputCharset != "")
            $bufSignSrc = $bufSignSrc . "inputCharset=" . $inputCharset . "&";
        if ($pickupUrl != "")
            $bufSignSrc = $bufSignSrc . "pickupUrl=" . $pickupUrl . "&";
        if ($receiveUrl != "")
            $bufSignSrc = $bufSignSrc . "receiveUrl=" . $receiveUrl . "&";
        if ($version != "")
            $bufSignSrc = $bufSignSrc . "version=" . $version . "&";
        if ($language != "")
            $bufSignSrc = $bufSignSrc . "language=" . $language . "&";
        if ($signType != "")
            $bufSignSrc = $bufSignSrc . "signType=" . $signType . "&";
        if ($merchantId != "")
            $bufSignSrc = $bufSignSrc . "merchantId=" . $merchantId . "&";
        if ($payerName != "")
            $bufSignSrc = $bufSignSrc . "payerName=" . $payerName . "&";
        if ($payerEmail != "")
            $bufSignSrc = $bufSignSrc . "payerEmail=" . $payerEmail . "&";
        if ($payerTelephone != "")
            $bufSignSrc = $bufSignSrc . "payerTelephone=" . $payerTelephone . "&";
        if ($payerIDCard != "")
            $bufSignSrc = $bufSignSrc . "payerIDCard=" . $payerIDCard . "&";
        if ($pid != "")
            $bufSignSrc = $bufSignSrc . "pid=" . $pid . "&";
        if ($orderNo != "")
            $bufSignSrc = $bufSignSrc . "orderNo=" . $orderNo . "&";
        if ($orderAmount != "")
            $bufSignSrc = $bufSignSrc . "orderAmount=" . $orderAmount . "&";
        if ($orderCurrency != "")
            $bufSignSrc = $bufSignSrc . "orderCurrency=" . $orderCurrency . "&";
        if ($orderDatetime != "")
            $bufSignSrc = $bufSignSrc . "orderDatetime=" . $orderDatetime . "&";
        if ($orderExpireDatetime != "")
            $bufSignSrc = $bufSignSrc . "orderExpireDatetime=" . $orderExpireDatetime . "&";
        if ($productName != "")
            $bufSignSrc = $bufSignSrc . "productName=" . $productName . "&";
        if ($productPrice != "")
            $bufSignSrc = $bufSignSrc . "productPrice=" . $productPrice . "&";
        if ($productNum != "")
            $bufSignSrc = $bufSignSrc . "productNum=" . $productNum . "&";
        if ($productId != "")
            $bufSignSrc = $bufSignSrc . "productId=" . $productId . "&";
        if ($productDescription != "")
            $bufSignSrc = $bufSignSrc . "productDescription=" . $productDescription . "&";
        if ($ext1 != "")
            $bufSignSrc = $bufSignSrc . "ext1=" . $ext1 . "&";
        if ($ext2 != "")
            $bufSignSrc = $bufSignSrc . "ext2=" . $ext2 . "&";
        if ($payType != "")
            $bufSignSrc = $bufSignSrc . "payType=" . $payType . "&";
        if ($issuerId != "")
            $bufSignSrc = $bufSignSrc . "issuerId=" . $issuerId . "&";
        if ($pan != "")
            $bufSignSrc = $bufSignSrc . "pan=" . $pan . "&";
        $bufSignSrc = $bufSignSrc . "key=" . $key; //key为MD5密钥，密钥是在通联支付网关会员服务网站上设置。

        $signMsg = strtoupper(md5($bufSignSrc));
        require_once("allinpay/pay.php");
        exit();
    }

    /**
     * 响应操作
     */
    function respond()
    {
        include_once ("allinpay/php_rsa.php");
        include_once ("allinpay/php_sax.php");
        $merchantId = $_POST["merchantId"];
        $version = $_POST['version'];
        $language = $_POST['language'];
        $signType = $_POST['signType'];
        $payType = $_POST['payType'];
        $issuerId = $_POST['issuerId'];
        $paymentOrderId = $_POST['paymentOrderId'];
        $orderNo = $_POST['orderNo'];
        $orderDatetime = $_POST['orderDatetime'];
        $orderAmount = $_POST['orderAmount'];
        $payDatetime = $_POST['payDatetime'];
        $payAmount = $_POST['payAmount'];
        $ext1 = $_POST['ext1'];
        $ext2 = $_POST['ext2'];
        $payResult = $_POST['payResult'];
        $errorCode = $_POST['errorCode'];
        $returnDatetime = $_POST['returnDatetime'];
        $signMsg = $_POST["signMsg"];

        $bufSignSrc = "";
        if ($merchantId != "")
            $bufSignSrc = $bufSignSrc . "merchantId=" . $merchantId . "&";
        if ($version != "")
            $bufSignSrc = $bufSignSrc . "version=" . $version . "&";
        if ($language != "")
            $bufSignSrc = $bufSignSrc . "language=" . $language . "&";
        if ($signType != "")
            $bufSignSrc = $bufSignSrc . "signType=" . $signType . "&";
        if ($payType != "")
            $bufSignSrc = $bufSignSrc . "payType=" . $payType . "&";
        if ($issuerId != "")
            $bufSignSrc = $bufSignSrc . "issuerId=" . $issuerId . "&";
        if ($paymentOrderId != "")
            $bufSignSrc = $bufSignSrc . "paymentOrderId=" . $paymentOrderId . "&";
        if ($orderNo != "")
            $bufSignSrc = $bufSignSrc . "orderNo=" . $orderNo . "&";
        if ($orderDatetime != "")
            $bufSignSrc = $bufSignSrc . "orderDatetime=" . $orderDatetime . "&";
        if ($orderAmount != "")
            $bufSignSrc = $bufSignSrc . "orderAmount=" . $orderAmount . "&";
        if ($payDatetime != "")
            $bufSignSrc = $bufSignSrc . "payDatetime=" . $payDatetime . "&";
        if ($payAmount != "")
            $bufSignSrc = $bufSignSrc . "payAmount=" . $payAmount . "&";
        if ($ext1 != "")
            $bufSignSrc = $bufSignSrc . "ext1=" . $ext1 . "&";
        if ($ext2 != "")
            $bufSignSrc = $bufSignSrc . "ext2=" . $ext2 . "&";
        if ($payResult != "")
            $bufSignSrc = $bufSignSrc . "payResult=" . $payResult . "&";
        if ($errorCode != "")
            $bufSignSrc = $bufSignSrc . "errorCode=" . $errorCode . "&";
        if ($returnDatetime != "")
            $bufSignSrc = $bufSignSrc . "returnDatetime=" . $returnDatetime;
        $key = initPublicKey("/publickey.xml");
        $keylength = 1024;
        $verify_result = rsa_verify($bufSignSrc, $signMsg, $key[1][0], $key[2][0], $keylength, "sha1");
        $value = null;
        if ($verify_result) {
            $value = "victory";
        } else {
            $value = "failed";
        }
        $payvalue = null;
        $pay_result = false;
        if ($verify_result and $payResult == 1) {
            $pay_result = true;
            $payvalue = "victory";
        } else {
            $payvalue = "failed";
        }
        if ($pay_result) {
            order_paid($orderNo);
            return true;
        } else {
            return false;
        }
    }

    //--------------------获取通联支付会员id--------------------
    function get_tl_user_id($uid,$payment)
    {
        $signType = '0';
//商户号
        $merchantId = $payment[allinpay_m];
//用户编号
        $partnerUserId = $uid;
//秘钥
        $key = $payment[allinpay_key];
//$str = "signType=".$signType."&merchantId=".$merchantId."&partnerUserId=".$partnerUserId."&key=".$key;
        $str = "&signType=" . $signType . "&merchantId=" . $merchantId . "&partnerUserId=" . $partnerUserId . "&key=" . $key . "&";
//签名，设为signMsg字段值。
        $signMsg = strtoupper(md5($str));

//请求地址
        $url = 'https://cashier.allinpay.com/usercenter/merchant/UserInfo/reg.do';

        $argv = array(
            /*'version' => 'v1.3',*/
            'signType'      => $signType,
            'merchantId'    => $merchantId,
            'partnerUserId' => $partnerUserId,
            'signMsg'       => $signMsg
        );

        $index = 0;
        $params = "";
        foreach ($argv as $key => $value) {
            if ($index != 0) {
                $params .= '&';
            }
            $params .= $key . '=';
            $params .= urlencode($value);//对字符串进行编码转换
            $index += 1;
        }
        $length = strlen($params);
        $serverIP = "cashier.allinpay.com";
        $urlhost = $serverIP;
        $urlpath = '/usercenter/merchant/UserInfo/reg.do';
        $header = array();
        $header[] = 'POST ' . $urlpath . ' HTTP/1.0';
        $header[] = 'Host: ' . $urlhost;
        $header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
        $header[] = 'Accept-encoding: gzip';
        $header[] = 'Accept-language: en-us';
        $header[] = 'Content-Type: application/x-www-form-urlencoded';
        $header[] = 'Content-Length: ' . $length;
        $request = implode("\r\n", $header) . "\r\n\r\n" . $params;
        $pageContents = "";
        if (!$fp = pfsockopen('ssl://' . $urlhost, 443, $errno, $errstr, 10)) { 
        } else {
            fwrite($fp, $request);
            $inHeaders = true;//是否在返回头
            $atStart = true;//是否返回头第一行
            $ERROR = false;
            $responseStatus;//返回头状态
            while (!feof($fp)) {
                $line = fgets($fp, 2048);

                if ($atStart) {
                    $atStart = false;
                    preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m);
                    $responseStatus = $m[2];
                    /*print_r("<div style='padding-left:40px;'>");
                    print_r("<div>" . $line . "</div>");
                    print_r("</div>");*/
                    continue;
                }

                if ($inHeaders) {
                    if (strLen(trim($line)) == 0) {
                        $inHeaders = false;
                    }
                    continue;
                }

                if (!$inHeaders and $responseStatus == 200) {
                    //获得参数串
                    $pageContents = $line;

                }
            }
            fclose($fp);
        }

        $result = explode('&', $pageContents);
        if (is_array($result)) {
            foreach ($result as $element) {
                $temp = explode('=', $element);
            }
        }
        $res = json_decode($pageContents, true);
        return $res[userId];
    }
}

?>